{extend name="common/base" /}
{block name="body"} 
<main>
    <div class="container goods-select layui-row">
        <div class="goods-tab layui-col-md6 layui-col-xs12">
            <div class="show-img">
                <div class="swiper-wrapper">
                    {volist name="goods_detail.slider" id="slider"} 
                        <img class="swiper-slide" src="{$slider}" alt="">
                    {/volist}
                </div>
                <!-- <div class="swiper-button-prev"><img class="img-detail-prev hidden-xs"
                        src="images/goods-detail-left.png" alt=""></div>
                <div class="swiper-button-next">
                    <img class="img-detail-next hidden-xs" src="images/goods-detail-right.png" alt="">
                </div> -->
                <img class="img-detail-prev hidden-xs" src="__ROOT__/static/images/goods-detail-left.png" alt="">
                <img class="img-detail-next hidden-xs" src="__ROOT__/static/images/goods-detail-right.png" alt="">
            </div>
            <div class="goods-detail-content">
                <div class="swiper-wrapper">
                    {volist name="goods_detail.slider" id="slider"} 
                        <img class="swiper-slide" src="{$slider}" alt="">
                    {/volist}
 
                </div>
            </div>
            <img class="goods-detail-next hidden-xs" src="__ROOT__/static/images/goods-detail-right.png" alt="">
            <img class="goods-detail-prev hidden-xs" src="__ROOT__/static/images/goods-detail-left.png" alt="">
        </div>
        <div class="goods-info layui-col-md6 layui-col-xs12">
            <h1 class="good-info-title">{$goods_detail.name}</h1>
            <h2 class="good-info-price" id="price">${$goods_detail.price_selling}</h2>
            <div class="goods-color-option">
           
            
                <!-- 动态渲染颜色选项 -->
                <p>color</p>
                <ul class="layui-row" id="color-options">
                    {volist name="goods_detail.specs[0]['list']" id="color"}
                    <li class="layui-col-md2 layui-col-xs5 spec-option {if $key == 0}  goods-options-active {/if}" 
                        data-type="颜色" 
                        data-value="{$color.name}" 
                        data-unid="{$color.unid}" >
                        {$color.name}
                    </li>
                    {/volist}
                </ul>
            
                <!-- 动态渲染尺码选项 -->
                <p>size</p>
                <ul class="layui-row" id="size-options">
                    {volist name="goods_detail.specs[1]['list']" id="size"}
                    <li class="layui-col-md2 layui-col-xs5 spec-option {if $key == 0}  goods-options-active {/if}" 
                        data-type="尺码" 
                        data-value="{$size.name}" 
                        data-unid="{$size.unid}" >
                        {$size.name}
                    </li>
                    {/volist}
                </ul>
            </div>
            
            <div class="add-to-cart" id="add-to-cart" lay-on="add-to-cart"><img src="__ROOT__/static/images/shopping-cart.png" alt="">Add to cart
            </div>
            <div class="add-to-collect collect"   data-code="{$goods_detail.code}" >
               
                {if $goods_detail.is_collect} 
                    <img src="__ROOT__/static/images/cancel-heart.png"  alt="">
                    <span style="margin-left: 10px;">cancel</span>
                         {else /} 
                    <img src="__ROOT__/static/images/heart.png" alt="">
                    <span style="margin-left: 10px;">collect</span>
                {/if}

            </div>
            <div class="add-to-cart"><img src="__ROOT__/static/images/shopping-cart.png" alt="">Buy Now
            </div>
        </div>
    </div>
    <div class="goods-detail-info container">
        <ul>
            <li>
                <p>Item information:</p>
                <span>{$goods_detail.remark}</span>
            </li>
            <li>
                <p>Color category:</p>
                <span>
                    {if isset($goods_detail.specs[0]['list']) && !empty($goods_detail.specs[0]['list'])}
                        {volist name="goods_detail.specs[0]['list']" id="color" key="k"}
                            {$color.name}{if $k < count($goods_detail.specs[0]['list'])} / {/if}
                        {/volist}
                    {else}
                        No color available
                    {/if}
                </span>
            </li>
            <li>
                <p>material quality:</p>
                <span>{$goods_detail.material_quality|default=''}</span>
            </li>
            <li>
                <p>size:</p>
                <span>
                    {if isset($goods_detail.specs[1]['list']) && !empty($goods_detail.specs[1]['list'])}
                        {volist name="goods_detail.specs[1]['list']" id="size" key="k"}
                            {$size.name}{if $k < count($goods_detail.specs[1]['list'])} / {/if}
                        {/volist}
                    {else}
                        No size available
                    {/if}
                </span>
            </li>
        </ul>
    </div>
    <!-- 评论部分 -->
    <div class="goods-comments container">
        <div class="layui-tab">
            <ul class="layui-tab-title">
                <li class="layui-this">All reviews</li>
                <li>Latest evaluation</li>
            </ul>
            <p class="add-comments comment"  lay-on="add_comments">
                <img src="__ROOT__/static/images/add-comments.png" />Add Comment
            </p>
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <ul>
                        {if count($goods_detail.comments)}
                            {volist name="goods_detail.comments" id="comment"} 
                                <li>
                                    <div class="comments-avatar">
                                        <img src="{$comment.avatar}" alt="">
                                        <div>
                                            <div class="user-info">
                                                <p>
                                                    <span class="user-name">{$comment.user_name}</span>
                                                    <span class="comments-time"> {$comment.create_time}</span>
                                                </p>
                                                <div>
                                                    {for start="1" end="6"}
                                                        <img src="__ROOT__/static/images/{if $i <= $comment.rate}good-detail-star{else}goods-detail-unlike-star{/if}.png" alt="Star">
                                                    {/for}
                                                   
                                                </div>
                                            </div>
                                            <p class="comments-content">
                                                {$comment.content}
                                            </p>
                                            <div class="comments-opration">
                                                <span class="comments-reply" data-comment-id="{$comment.id}">Reply</span>
                                                <img class="comments-like" data-comment-id="{$comment.id}" data-type="1" src="__ROOT__/static/images/goods-like.png" alt="">
                                                <span class="like-number like-numbers">{$comment.up_num|default=0}</span>
                                                <img class="comments-unlike" data-comment-id="{$comment.id}" data-type="2" src="__ROOT__/static/images/goods-unlike.png" alt="">
                                                <span class="like-number  unlike-numbers">{$comment.down_num|default=0}</span>
                                            </div>
                                            {if count($comment.reply)} 
                                                {volist name="comment.reply" id="reply"} 
                                                    <div class="comments-avatar">
                                                        <img src="{$reply.avatar}" alt="">
                                                        <div>
                                                            <div class="user-info">
                                                                <p>
                                                                    <span class="user-name">{$reply.user_name}</span>
                                                                    <span class="comments-time"> {$reply.create_time}</span>
                                                                </p>
                                                            </div>
                                                            <p class="comments-content">
                                                                {$reply.content}
                                                            </p>
                                                        </div>
                                                    </div>
                                                {/volist} 
                                            {/if}
                                        </div>
                                </li>
                            {/volist}
                        {/if}
                    </ul>
                </div>
                <div class="layui-tab-item">
                    <ul>
                        {if count($goods_detail.last_comments)}
                            {volist name="goods_detail.last_comments" id="last_comments"} 
                                <li>
                                    <div class="comments-avatar">
                                        <img src="{$last_comments.avatar}" alt="">
                                        <div>
                                            <div class="user-info">
                                                <p>
                                                    <span class="user-name">{$last_comments.user_name}</span>
                                                    <span class="comments-time">{$last_comments.create_time}</span>
                                                </p>
                                                <div>
                                                    {for start="1" end="5"}
                                                        {if $i <= $last_comments.rate}
                                                            <img src="__ROOT__/static/images/good-detail-star.png" alt="Star">
                                                        {else /}
                                                            <img src="__ROOT__/static/images/goods-detail-unlike-star.png" alt="Star">
                                                        {/if}
                                                    {/for}
                                                </div>
                                            </div>
                                            <p class="comments-content">
                                                {$last_comments.content}
                                            </p>
                                            <div class="comments-opration">
                                                <span class="comments-reply">Reply</span>
                                                <img class="comments-like" data-comment-id="{$comment.id}" data-type="1" src="__ROOT__/static/images/goods-like.png" alt="">
                                                <span class="like-number like-numbers">{$last_comments.up_num|default=0}</span>
                                                <img class="comments-unlike" data-comment-id="{$comment.id}" data-type="2" src="__ROOT__/static/images/goods-unlike.png" alt="">
                                                <span class="like-number unlike-numbers">{$last_comments.down_num|default=0}</span>
                                            </div>
                                            {if count($comment.reply)} 
                                                {volist name="comment.reply" id="reply"} 
                                                    <div class="comments-avatar">
                                                        <img src="{$reply.avatar}" alt="">
                                                        <div>
                                                            <div class="user-info">
                                                                <p>
                                                                    <span class="user-name">{$reply.user_name}</span>
                                                                    <span class="comments-time"> {$reply.create_time}</span>
                                                                </p>
                                                            </div>
                                                            <p class="comments-content">
                                                                {$reply.content}
                                                            </p>
                                                        </div>
                                                    </div>
                                                {/volist} 
                                            {/if}
                                        </div>
                                </li>
                            {/volist}
                        {/if}
                    </ul>
                </div>
            </div>
        </div>
    </div>

</main>
{/block}

{block name="js"} 
<script>
  $(document).ready(function () {
        // Initialize global variables
        let selectedSpecs = {
            '颜色': $('ul#color-options li.goods-options-active').data('value'),
            '尺码': $('ul#size-options li.goods-options-active').data('value'),
        };

        // Backend product combination data
        const items = {$goods_detail.items|json_encode|raw};

        // Update price and stock
        function updateGoodsInfo() {
            const selectedCombination = `颜色::${selectedSpecs['颜色']};;尺码::${selectedSpecs['尺码']}`;
            const matchedItem = items.find(item => item.gspec === selectedCombination);

            if (matchedItem) {
                $('#price').text(`$${matchedItem.price_selling}`);
                $('#stock').text(matchedItem.stock_total);
                $('#add-to-cart').attr('data-ghash', matchedItem.ghash);
                $('#add-to-cart').data('ghash', matchedItem.ghash); // Save ghash
            } else {
                $('#price').text('Out of stock');
                $('#stock').text('0');
                $('#add-to-cart').data('ghash', null); // Clear ghash
                $('#add-to-cart').attr('data-ghash', null);
            }
        }

        // Click on specification option
        $('.spec-option').click(function () {
            const type = $(this).data('type');
            const value = $(this).data('value');

            // Update active state
            $(this).siblings().removeClass('goods-options-active');
            $(this).addClass('goods-options-active');

            // Update selected specifications
            selectedSpecs[type] = value;

            // Update page information
            updateGoodsInfo();
        });

        // Add to cart
        $('#add-to-cart').click(function () {
            const ghash = $(this).data('ghash');
            if (!ghash) {
                layer.msg('Please select a valid specification combination!', { icon: 2 });
                return;
            }

            const data = {
                ghash: ghash,
                number: 1, // Default quantity is 1
            };

            // Send AJAX request
            ajaxRequest('/add_cart', data, 'POST', this, function (response) {
          
                if (response.code == 1) {
                    layer.msg('Successfully Added To The Shopping Cart', { icon: 1 });
                } else {
                    layer.msg(response.message || 'Operation Failed!', { icon: 2 });
                }
            });
        
        });

        // Update information on page load
        updateGoodsInfo();


        $(document).on('click', '.collect', function() {
            var is_login = "{$is_login}";
            var that = this;
            if (!is_login) {
                layer.msg('Please login first', {icon: 2, time: 2000}, function() {
                    window.location.href = '/login'; // Replace with target URL
                });
                return;
            }
            
            var id = $(this).data('id');
            var code = $(this).data('code');
            var data = { gcode: code };
            
            // Make the AJAX request
            ajaxRequest('/collect', data, 'POST', this, function (response) {
            
                // Assuming the response will indicate if the item was successfully collected
                if (response.code == 1) {
                    // Toggle image and text
                    var img = $(that).find('img');
                    var span = $(that).find('span');
                    
                    // Check if currently collected (e.g., based on image or state)
                    if (span.text() === 'collect') {
                        // Change to "cancel" state
                        img.attr('src', '__ROOT__/static/images/cancel-heart.png');
                        span.text('cancel');
                    } else {
                        // Change to "collect" state
                        img.attr('src', '__ROOT__/static/images/heart.png');
                        span.text('collect');
                    }
                    
                    // Optional success message
                    layer.msg('SUCCESS', {icon: 1, time: 2000});
                }
            });
        });

        // 评价弹窗
        function openCommentModal(options = {}) {
                var rate = layui.rate;
                var layer = layui.layer;
                var form = layui.form;

                const { commentId = null, onSubmit = null } = options;

                // 打开弹窗
                layer.open({
                    type: 1,
                    area: ['600px', 'auto'], // 宽高
                    title: false, // 不显示标题栏
                    closeBtn: 0, // 不显示关闭按钮
                    shadeClose: true, // 点击遮罩关闭层
                    skin: 'add_comments_dialog', // 自定义样式类名
                    content: `
                        <form class="layui-form" id="comment-form" onSubmit="return false;">
                            <div class="layui-form-item">
                                <label class="layui-form-label">Message</label>
                                <div class="layui-input-block">
                                    <textarea class="layui-textarea massage" name="message" required></textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">Star</label>
                                <div class="layui-input-block rate"></div>
                            </div>
                            <div class="layui-form-item center_box">
                                <button  class="btn" id="submit-comment">Submit</button>
                            </div>
                        </form>
                    `
                });

                // 渲染评分组件
                let rating = 0; // 默认评分
                rate.render({
                    elem: '.rate',
                    value: 0, // 默认星级
                    setText: function (value) {
                        rating = value; // 更新星级评分
                    }
                });

                // 提交评价
                $(document).on('click', '#submit-comment', function () {
                    var message = $('#comment-form .massage').val().trim();

                    if (!message) {
                        layer.msg('Please enter your message.', { icon: 2 });
                        return;
                    }

                    if (rating === 0) {
                        layer.msg('Please select a rating.', { icon: 2 });
                        return;
                    }

                    // 数据准备
                    var data = {
                        message: message,
                        rating: rating,
                        goods_id : "{$goods_detail.id}",
                        ghash:   $('#add-to-cart').data('ghash')
                    };

                    if (commentId) {
                        data.commentId = commentId; // 附加评论 ID
                    }

                    if (onSubmit) {
                        onSubmit(data); // 调用回调函数
                    }
                });

                // 取消评价
                $(document).on('click', '#cancel-comment', function () {
                    layer.closeAll(); // 关闭弹窗
                });
            }


        //普通评价
        $(document).on('click', '.comment', function () {
            openCommentModal({
                onSubmit: function (data) {
                    // 发送 AJAX 请求
                    ajaxRequest('/submit-comment', data, 'POST', this, function (response) {
                        if (response.code == 1) {
                            layer.msg('Successfully Added To The Shopping Cart', { icon: 1 });
                            layer.closeAll(); // 关闭弹窗
                        } else {
                            layer.msg(response.message || 'Operation Failed!', { icon: 2 });
                        }
                    });
                }
            });
        });
        $(document).on('click', '.comments-reply', function () {
            const commentId = $(this).data('comment-id');
            openCommentModal({
                commentId: commentId,
                onSubmit: function (data) {
                    // 发送 AJAX 请求
                    ajaxRequest('/submit-comment', data, 'POST', this, function (response) {
                        if (response.code == 1) {
                            layer.msg('Successfully Added To The Shopping Cart', { icon: 1 });
                            layer.closeAll(); // 关闭弹窗
                        } else {
                            layer.msg(response.message || 'Operation Failed!', { icon: 2 });
                        }
                    });
                }
            });
        });

          // 点赞事件
    $(document).on('click', '.comments-like', function () {
        const $this = $(this);
        const commentId = $this.data('comment-id');
        const type = $this.data('type');
        const data = { commentId: commentId, type: type };
        ajaxRequest('/comments-like', data, 'POST', this, function (response) {
            if (response.code == 1) {
                const count = $this.next('.like-numbers');
                count.text(parseInt(count.text()) + 1);
            } else {
                layer.msg(response.message || 'Operation failed', { icon: 2 })
            }
        });

    });

    // 点踩事件
    $(document).on('click', '.comments-unlike', function () {
        const $this = $(this);
        const commentId = $this.data('comment-id');
        const type = $this.data('type');
        const data = { commentId: commentId, type: type };
        ajaxRequest('/comments-like', data, 'POST', this, function (response) {
            if (response.code == 1) {
                const count = $this.next('.unlike-numbers');
                count.text(parseInt(count.text()) + 1);
            } else {
                layer.msg(response.message || 'Operation failed', { icon: 2 })
            }
        });

    });




    });

</script>
{/block}
